<template>
  <div
    style="width: 100%; position: relative; float: left;display: flex;flex-direction: column;overflow: hidden;padding: 5px;">
    <div style="padding: 5px;">
      <template v-if="bmInfo.length > 1">
        <el-text class="mx-1">部门：</el-text>

        <el-select v-model="department" placeholder="请选择部门名称" style="width: 200px;margin-right: 15px;">
          <el-option v-for="(item, index) in departmentData" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </template>


      <el-text class="mx-1">年份：</el-text>
      <!-- <el-input
          v-model="inputKeyWord"
          style="width: 200px"
          placeholder="请输入关键词"
        /> -->
      <el-select v-model="selectedYearValue" placeholder="请选择年份" style="width: 200px;margin-right: 15px;">
        <el-option v-for="item in YearOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-text class="mx-1">警报单类型：</el-text>
      <!-- <el-input
          v-model="inputUserName"
          style="width: 200px"
          placeholder="请输入用户名"
        /> -->
      <el-select v-model="selectedWarnValue" placeholder="请选择警报类型" style="width: 200px;margin-right: 15px;">
        <el-option v-for="item in WarnOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <!-- <el-button type="primary" plain style="margin: 0 15px">检索</el-button> -->
      <!-- <el-button type="primary" plain>新增用户</el-button> -->
    </div>
    <!-- 角色管理 -->
    <div style="overflow: auto;">
      <el-table :data="tableDataCom" style="width: 100%; margin-bottom: 10px" row-key="id" border default-expand-all
        stripe>
        <el-table-column prop="id" label="编号" sortable />
        <el-table-column prop="date" label="警报时间" sortable />
        <el-table-column prop="value" label="警报类型" sortable>
          <template #default="{ row }">
            <span :style="{ color: getColor(row) }">
              {{ row.value }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="url" label="警报文件" sortable />
        <el-table-column prop="state" label="启用状态" sortable>
          <template #default="{ row }">
            <el-switch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" v-model="row.state"
              :active-value="1" :inactive-value="0" size="" active-text="正常" inactive-text="禁用" inline-prompt
              @change="handleStatus(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- <el-button size="small" type="default" @click="deleteRow(scope.$index)" plain>查看</el-button> -->
            <el-button size="small" type="primary" @click="dowRow(scope.row)" plain>下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
        :page-sizes="[5, 10, 15]" layout="sizes, prev, pager, next" />
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, onMounted, watch, computed, warn } from "vue";
import {
  getAllDepartment,
  getAllUser,
  getDisasterByYear,
  searchDisasterByTypeAndYearAndDepartment,
  updateStateById,
} from "../../network/net.js";
import { formatTime } from "../../utils/cTime.js";
// import { bmInfo, bm } from "@/stores/chun.js";

let bm = sessionStorage.getItem("bm");
let bmInfo = sessionStorage.getItem("bmInfo");

bm = ref(bm);
bmInfo = ref(JSON.parse(bmInfo));

let token = sessionStorage.getItem("token");

onMounted(() => {
  initAllDepartment()
})
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const StatusOptions = [
  { value: "1", label: "正常" },
  { value: "0", label: "禁用" },
];
const selectedYearValue = ref("2024");
const YearOptions = [
  { value: "2024", label: "2024" },
  { value: "2023", label: "2023" },
  { value: "2022", label: "2022" },
  { value: "2021", label: "2021" },
  { value: "2020", label: "2020" },
  { value: "2019", label: "2019" },
];
const selectedWarnValue = ref("风暴潮警报");
const WarnOptions = [
  { value: "风暴潮警报", label: "风暴潮警报" },
  { value: "海浪警报", label: "海浪警报" },
];
// 当前选中的节点 ID
const selectedNode = ref(null);
// const handleNodeClick = (data, node) => {
//   // 阻止默认行为，即阻止节点折叠
//   node.expand();
// };
// 处理节点点击事件
const handleNodeClick = (data, node) => {
  selectedNode.value = data.id;
  // 阻止默认行为，即阻止节点折叠
  node.expand();
};
const expandedkeys = ref([]);
const checkedkeys = ref([]);
const defaultProps = {
  children: "children",
  label: "name",
};
const treeData = ref();
treeData.value = [
  {
    id: "all",
    name: "全部",
    children: [],
  },
];
// 获取部门数据
// getAllDepartment(token).then((res) => {
//   if (res?.data?.code == "200" && res?.data?.data?.length > 0) {
//     treeData.value[0].children = res?.data?.data;
//   }
// });
const tableData = ref([]);
// 获取用户数据
// getAllUser(token).then((res) => {
//   if (res?.data?.code == "200" && res?.data?.data?.length > 0) {
//     let arr = res?.data?.data;
//     arr.map((item) => {
//       item.departmentName = item.department.name;
//       item.roleName = item.role.name;
//       item.pw = "********";
//       return item;
//     });
//     tableData.value = arr;
//   }
// });
let type = selectedWarnValue.value == "海浪警报" ? "wave" : "storm";
const docurl = import.meta.env.VITE_backurl_warndoc;
// getDisasterByYear(token, type, selectedYearValue.value).then((res) => {
//   tableData.value = [];
//   let arr = [];
//   res.data.data?.forEach((item, index) => {
//     let str = "";
//     if (item.warnName == "解除") {
//       str = "通报";
//     } else if (item.warnName == "消息") {
//       str = "";
//     } else {
//       str = "警报";
//     }

//     arr.push({
//       id: index + 1,
//       date: formatTime(item.publishDate).split(":")[0],
//       // value: (activeTab.value == '海浪警报' ? '海浪' : '风暴潮') + item.warnName + str,
//       value: item.warnName + str,
//       // url: 'http://192.168.8.127:8085/' + item.warnUrl
//       url: docurl + item.warnUrl, //
//       status: "1",
//       editing: false,
//     });
//   });
//   tableData.value = arr;
//   total.value = arr.length;
// });

const handleStatus = (item) => {

  updateStateById(token, {
    id: item.warnId,
    state: item.state,
  }).then((res) => {
    if (res?.data?.code == "200") {
      ElMessage.success("修改成功");
    }
  });

}
const saveEdit = (row) => {
  row.editing = false;
  ElMessage.success("编辑成功");
};

const deleteRow = (index) => {
  ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      tableData.splice(index, 1);
      userTableData.value = [...tableData];
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const dowRow = (row) => {
  window.open(row.url);

  return
  window.open(tableData.value[index].url);
};

const getColor = (row) => {
  if (row?.value?.includes("解除")) {
    return "#7ED321"
  } else if (row?.value?.includes("消息")) {
    return "#9B9B9B"
  } else if (row?.value?.includes("红色")) {
    return "#D0021B"
  } else if (row?.value?.includes("橙色")) {
    return "#F5A623"
  } else if (row?.value?.includes("黄色")) {
    return "#F8E71C"
  } else if (row?.value?.includes("蓝色")) {
    return "#4A90E2"
  } else {
    return "black"
  }

};

const department = ref("");
const departmentData = ref([]);
const initAllDepartment = () => {
  getAllDepartment(token).then((res) => {
    if (res?.data?.code == "200" && res?.data?.data?.length > 0) {
      let arr = res?.data?.data.filter((item) => item.status != 0);
      departmentData.value = arr.filter((item) => item.name != "预报中心");
      department.value = res?.data?.data[1].id;
    }
  });
}

const tableDataCom = computed(() => {
  // pageSize 
  return tableData.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
})

watch([department, selectedYearValue, selectedWarnValue], () => {
  let type = selectedWarnValue.value == "海浪警报" ? "wave" : "storm";
  let bmId = bmInfo.value.find(item => item.name == bm.value).id;
  searchDisasterByTypeAndYearAndDepartment(token, {
    type: type,
    year: selectedYearValue.value,
    departId: department.value==''?bmId:department.value
  }).then((res) => {

    tableData.value = [];
    let arr = [];
    res.data.data?.forEach((item, index) => {
      let str = "";
      if (item.warnName == "解除") {
        str = "通报";
      } else if (item.warnName == "消息") {
        str = "";
      } else {
        str = "警报";
      }

      arr.push({
        id: index + 1,
        warnId: item.disasterId,
        date: formatTime(item.publishDate).split(":")[0],
        value: item.warnName + str,
        url: `${docurl}/${item.parentDirectory}/${item.warnUrl}`,
        state: item.state,
        editing: false,
        parentDirectory: item.parentDirectory,
      });
    });
    tableData.value = arr;
    total.value = arr.length;
  });
}, {
  immediate: true
})
</script>
<style lang="less" scoped></style>
